import { ElMessage } from 'element-plus'
import {  reactive, toRefs } from 'vue'
import {downLoad} from '../../../utils/common'
import request from '@/utils/request'
import moment from 'moment-mini'

export default function excelExport(props) {
  const _data = reactive({
    exportLoading: false, //下载加载状态
    fileList: [], //导入文件集合
    fileType: ['.xls', '.xlsx'], //下载文件类型
    fileTypeIndex: '.xls',
    downLoadName: '', //下载文件名
    downLoadPop: false //下载文件弹窗
  })

  //导出初始化
  const downLoadInit = () => {
    _data.downLoadPop = true
    _data.downLoadName = ''
  }

  //导出数据
  const exportComfirn = (type) => {
    let d = { ...props.params }
    return new Promise((resolve, reject) => {
      if (type == 0) {
        resolve({
          fileName: moment().format('yyyy-MM-DD'),
          fileType: '.xls',
          ...d
        })
      } else {
        if (!_data.downLoadName) {
          ElMessage.error('请输入导出文件名')
          return
        }
        resolve({
          fileName: _data.downLoadName,
          fileType: _data.fileTypeIndex,
          ...d
        })
      }
    }).then((d) => {
      _data.exportLoading = true
      let axios_config = {
        url: props.downLoadUrl,
        method: props.downLoadMethod,
        responseType: props.responseType,
        data: {
          ...d,
          fileType: d.fileType === 'xls' ? 0 : 1
        }
      }
      request(axios_config)
        .then((res) => {
          let { data } = res
          // 如果不是blob模式并且有下载链接，将使用地址进行跳转下载
          if(!props.isDownLoadFile && data.data){
            window.location.href = data.data
          }else{
            downLoad(data, d.fileName, d.fileType)
          }
          _data.downLoadPop = false
          _data.downLoadName = ''
          _data.exportLoading = false
        })
        .catch(() => {
          _data.exportLoading = false
        })
    })
  }

  return {
    ...toRefs(_data),
    downLoadInit,
    exportComfirn
  }
}
